package com.example.demomk.Utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.os.Handler;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.demomk.R;
import com.example.demomk.databinding.CustomNavBarBinding;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CustomNavBar {
    private Activity activity;
    private View navBarView;
    private TextView tvTime, tvBatteryPercent;
    private Handler timeHandler;
    public ImageView icon ,wifi_icon;
    private BroadcastReceiver wifiReceiver;
    private BroadcastReceiver batteryReceiver;
    private CustomNavBarBinding  binding;
    private ConnectivityManager.NetworkCallback networkCallback;
    private ConnectivityManager connectivityManager;
    public CustomNavBar(Activity activity) {
        this.activity = activity;
        initNavBar();
    }

    private void initNavBar() {
        binding = CustomNavBarBinding.inflate(LayoutInflater.from(activity));
        //  充电图标控件

        // 1. 加载自定义导航栏布局
        LayoutInflater inflater = LayoutInflater.from(activity);
        CustomNavBarBinding binding = CustomNavBarBinding.inflate(inflater, null, false);
        navBarView = binding.getRoot();

        // 2. 绑定控件
        tvTime = binding.tvTime;
        tvBatteryPercent = binding.tvBatteryPercent;
        icon = binding.ivBatteryIcon;
        wifi_icon = binding.ivWifiIcon;

        ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
        decorView.addView(navBarView, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));

        // 4. 启动时间更新
        startTimeUpdate();

        // 5. 注册电量监听
        registerBatteryReceiver();
        //  注册WiFi监听
        registerWifiReceiver();
    }

    // 更新时间（每秒刷新）
    private void startTimeUpdate() {
        timeHandler = new Handler();
        // 1. 立即显示当前时间
        String initialTime = new SimpleDateFormat("YYYY-MM-dd HH:mm", Locale.getDefault()).format(new Date());
        tvTime.setText(initialTime);

        // 2. 计算第一次延迟时间，对齐下一分钟
        long delay = 60_000 - (System.currentTimeMillis() % 60_000);

        timeHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 3. 后续每60秒刷新一次，保持与系统时间同步
                String time = new SimpleDateFormat("YYYY-MM-dd HH:mm", Locale.getDefault()).format(new Date());
                tvTime.setText(time);
                timeHandler.postDelayed(this, 60_000);
            }
        }, delay);
    }

    // 监听电量变化
    private void registerBatteryReceiver() {
        batteryReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;

                tvBatteryPercent.setText(level + "%");
                // 根据是否充电更换图片
                if (isCharging) {
                    icon.setImageResource(R.drawable.chongdian);
                } else {
                    if (level >= 90) {
                       icon.setImageResource(R.drawable.dian100);
                    }else if (level >= 70) {
                       icon.setImageResource(R.drawable.dian70);
                    }
                    else if (level >= 30) {
                       icon.setImageResource(R.drawable.dian50);
                    } else {
                       icon.setImageResource(R.drawable.dianfloat);
                    }
                }
            }
        };
        activity.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    private void registerWifiReceiver() {
        wifiReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

                boolean isWifiConnected = false;
                if (activeNetwork != null && activeNetwork.isConnected()) {
                    isWifiConnected = (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);
                }

                // 更新 UI 或执行其他操作
                if (isWifiConnected) {
//                    Log.d("CustomNavBar", "当前使用 WiFi");
                    // 可以设置一个 WiFi 图标或状态提示
                    wifi_icon.setVisibility(View.VISIBLE);
                } else {
//                    Log.d("CustomNavBar", "当前不是 WiFi");
                    wifi_icon.setVisibility(View.GONE);
                }
            }
        };

        activity.registerReceiver(wifiReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }




    // 设置用户名
    public void setUsername(String username) {
        TextView tvUsername = navBarView.findViewById(R.id.tvUsername);
        tvUsername.setText(username);
    }

    // 销毁时释放资源
    public void destroy() {
        if (timeHandler != null) {
            timeHandler.removeCallbacksAndMessages(null);
        }
        if (wifiReceiver != null) {
            try {
                activity.unregisterReceiver(wifiReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (batteryReceiver != null) {
            try {
                activity.unregisterReceiver(batteryReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}